package com.zjitc.utils;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Message.RecipientType;
import javax.mail.Session;

import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;


/**
 * Create By IntelliJ IDEA
 *
 * @author: myq
 * @create-Time: 2017/11/7  11:39
 */
public class Mail {

  /**
   * 从那个邮箱发送   邮箱的授权密码   所使用的协议   host  port端口
   */
  private static final String KEY_USERNAME = "username";
  private static final String KEY_PASSWORD = "password";
  private static final String KEY_PROTOCOL = "mail.transport.protocol";
  private static final String KEY_HOST = "mail.smtp.host";
  private static final String KEY_PORT = "mail.smtp.port";
//    private static final String KEY_AUTH = "mail.smtp.auth";

  private static final Properties DEFAULT_PROPERTIES;
  private Properties properties;


  static {
    InputStream stream = Mail.class.getClassLoader().getResourceAsStream("mail.properties");
    //获取配置文件中的key value
    DEFAULT_PROPERTIES = new Properties();
    try {
      DEFAULT_PROPERTIES.load(stream);
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }


  public Mail(String username, String password, String protocol,
      String host, String port) {
    properties = new Properties();
    properties.setProperty(KEY_USERNAME, username);
    properties.setProperty(KEY_PASSWORD, password);
    properties.setProperty(KEY_PROTOCOL, protocol);
    properties.setProperty(KEY_HOST, host);
    properties.setProperty(KEY_PORT, port);
//        properties.setProperty(KEY_AUTH,"true");

  }

  public Mail() {
    properties = DEFAULT_PROPERTIES;
  }

  public void send(String toMail, String subject, String content) throws MessagingException {
    Session session = Session.getDefaultInstance(properties);
    Message message = new MimeMessage(session);

    message.setFrom(new InternetAddress(properties.getProperty(KEY_USERNAME)));
    //目标邮箱
    message.addRecipient(RecipientType.TO, new InternetAddress(toMail));
    //主题
    message.setSubject(subject);
    //内容以及编码方式
    message.setContent(content, "text/html;charset=utf-8");

    message.saveChanges();

    Transport transport = session.getTransport(properties.getProperty(KEY_PROTOCOL));
    transport.connect(properties.getProperty(KEY_HOST),
        properties.getProperty(KEY_USERNAME),
        properties.getProperty(KEY_PASSWORD));
    transport.sendMessage(message, message.getAllRecipients());
    transport.close();
  }
}